import express from 'express'
import https from 'https'
import http from 'http'
import fs from 'fs'
import path from 'path'
import {fileURLToPath} from 'url'
import cors from 'cors'
import dotenv from 'dotenv'
import {testConnection} from './config/database.js'
import authRoutes from './routes/auth.js'
import exhibitionRoutes from './routes/exhibitions.js'
import orderRoutes from './routes/orders.js'
import paymentRoutes from './routes/payment.js'
import paymentV3Routes from './routes/paymentV3.js'
import wechatRoutes from './routes/wechat.js'
import contactRoutes from './routes/contacts.js'

dotenv.config()

const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)

const app = express()
const PORT = process.env.PORT || 3000
const HTTPS_PORT = process.env.HTTPS_PORT || 3443
const USE_HTTPS = process.env.USE_HTTPS === 'true'

// 中间件
app.use(express.json())
app.use(express.urlencoded({extended: true}))
// 支持 XML 格式（微信支付回调）
app.use(express.text({type: 'text/xml'}))

// CORS 配置
const allowedOrigins = process.env.ALLOWED_ORIGINS
  ? process.env.ALLOWED_ORIGINS.split(',')
  : ['http://localhost:10086']

app.use(
  cors({
    origin: function (origin, callback) {
      // 允许没有 origin 的请求（如移动应用、Postman）
      if (!origin) return callback(null, true)

      if (allowedOrigins.indexOf(origin) !== -1 || allowedOrigins.includes('*')) {
        callback(null, true)
      } else {
        callback(new Error('不允许的跨域请求'))
      }
    },
    credentials: true
  })
)

// 路由
app.get('/', (req, res) => {
  res.json({
    success: true,
    message: '艺术空间票务 API 服务',
    version: '1.0.0'
  })
})

app.use('/api/auth', authRoutes)
app.use('/api/exhibitions', exhibitionRoutes)
app.use('/api/orders', orderRoutes)
app.use('/api/payment', paymentRoutes)
app.use('/api/v3/payment', paymentV3Routes)
app.use('/api/wechat', wechatRoutes)
app.use('/api/contacts', contactRoutes)


// 404 处理
app.use((req, res) => {
  res.status(404).json({
    success: false,
    error: '接口不存在'
  })
})

// 错误处理
app.use((err, req, res, next) => {
  console.error('服务器错误:', err)
  res.status(500).json({
    success: false,
    error: err.message || '服务器内部错误'
  })
})

// 启动服务器
async function startServer() {
  // 测试数据库连接
  const dbConnected = await testConnection()

  if (!dbConnected) {
    console.error('❌ 无法连接到数据库，请检查配置')
    process.exit(1)
  }

  // 如果启用 HTTPS
  if (USE_HTTPS) {
    try {
      // SSL 证书路径
      const sslKeyPath = process.env.SSL_KEY_PATH || path.join(__dirname, '../ssl/private.key')
      const sslCertPath = process.env.SSL_CERT_PATH || path.join(__dirname, '../ssl/certificate.crt')

      // 检查证书文件是否存在
      if (!fs.existsSync(sslKeyPath) || !fs.existsSync(sslCertPath)) {
        console.error('❌ SSL 证书文件不存在')
        console.error(`   请确保以下文件存在：`)
        console.error(`   - ${sslKeyPath}`)
        console.error(`   - ${sslCertPath}`)
        console.error(`\n   或者设置 USE_HTTPS=false 使用 HTTP 模式`)
        process.exit(1)
      }

      // HTTPS 配置
      const httpsOptions = {
        key: fs.readFileSync(sslKeyPath),
        cert: fs.readFileSync(sslCertPath)
      }

      // 创建 HTTPS 服务器
      const httpsServer = https.createServer(httpsOptions, app)

      httpsServer.listen(HTTPS_PORT, () => {
        console.log(`\n🚀 HTTPS 服务器启动成功！`)
        console.log(`📍 地址: https://localhost:${HTTPS_PORT}`)
        console.log(`🌍 环境: ${process.env.NODE_ENV || 'development'}`)
        console.log(`🔒 SSL: 已启用`)
        printApiEndpoints()
      })

      // 可选：同时启动 HTTP 服务器，自动重定向到 HTTPS
      if (process.env.HTTP_REDIRECT === 'true') {
        const httpApp = express()
        httpApp.use((req, res) => {
          res.redirect(301, `https://${req.headers.host}${req.url}`)
        })
        httpApp.listen(PORT, () => {
          console.log(`🔄 HTTP 重定向服务器启动: http://localhost:${PORT} -> https://localhost:${HTTPS_PORT}`)
        })
      }
    } catch (error) {
      console.error('❌ HTTPS 服务器启动失败:', error.message)
      process.exit(1)
    }
  } else {
    // HTTP 模式
    app.listen(PORT, () => {
      console.log(`\n🚀 HTTP 服务器启动成功！`)
      console.log(`📍 地址: http://localhost:${PORT}`)
      console.log(`🌍 环境: ${process.env.NODE_ENV || 'development'}`)
      console.log(`⚠️  警告: 当前使用 HTTP 模式，生产环境请启用 HTTPS`)
      printApiEndpoints()
    })
  }
}

// 打印 API 端点信息
function printApiEndpoints() {
  console.log(`\n可用的 API 端点:`)
  console.log(`  POST   /api/auth/register          - 用户注册`)
  console.log(`  POST   /api/auth/login             - 用户登录`)
  console.log(`  GET    /api/auth/me                - 获取当前用户信息`)
  console.log(`  GET    /api/exhibitions            - 获取展览列表`)
  console.log(`  GET    /api/exhibitions/:id        - 获取展览详情`)
  console.log(`  GET    /api/exhibitions/:id/ticket-types - 获取票种列表`)
  console.log(`  POST   /api/orders                 - 创建订单`)
  console.log(`  GET    /api/orders/:orderNo        - 获取订单详情`)
  console.log(`  GET    /api/orders/phone/:phone    - 根据手机号查询订单`)
  console.log(`  PUT    /api/orders/:orderNo/status - 更新订单状态`)
  console.log(`  POST   /api/payment                - 创建支付订单 (V2)`)
  console.log(`  POST   /api/payment/notify         - 支付回调通知 (V2)`)
  console.log(`  GET    /api/payment/:orderNo       - 查询支付状态 (V2)`)
  console.log(`  POST   /api/payment/refund         - 申请退款 (V2)`)
  console.log(`  POST   /api/v3/payment             - 创建支付订单 (V3)`)
  console.log(`  POST   /api/v3/payment/notify      - 支付回调通知 (V3)`)
  console.log(`  GET    /api/v3/payment/:orderNo    - 查询支付状态 (V3)`)
  console.log(`  POST   /api/v3/payment/refund      - 申请退款 (V3)`)
  console.log(`  POST   /api/wechat/openid          - 获取用户 openid`)
  console.log(`\n`)
}

startServer()
